package j_log

import (
	"fmt"
	"log"
	"modbus-tools/init/global"
	"modbus-tools/utils/tools"
)

type LogLevel int

const (
	LOG_DEBUG   LogLevel = 0
	LOG_INFO    LogLevel = 1
	LOG_WARNING LogLevel = 2
	LOG_ERROR   LogLevel = 3
	LOG_FATAL   LogLevel = 4
)

func LogDebug(data []interface{}) {
	LogHandle(LOG_DEBUG, data)
}

func LogInfo(data []interface{}) {
	LogHandle(LOG_INFO, data)
}
func LogWarning(data []interface{}) {
	LogHandle(LOG_WARNING, data)
}

func LogError(data []interface{}) {
	LogHandle(LOG_ERROR, data)
}

func LogHandle(level LogLevel, a []interface{}) {
	levelName := ""
	switch level {
	case LOG_DEBUG:
		levelName = "debug"
	case LOG_INFO:
		levelName = "info"
	case LOG_WARNING:
		levelName = "warning"
	case LOG_ERROR:
		levelName = "error"
	case LOG_FATAL:
		levelName = "fatal"
	default:
		log.Fatalln("invalid console level")
	}
	s := ""
	s += fmt.Sprintf("[%s] <%s> ", tools.GetNow(), levelName)
	for _, v := range a {
		s += fmt.Sprintf("%v ", v)
	}
	s += fmt.Sprintf("\n")
	if global.ConsoleOutput && level >= LogLevel(global.ConsoleOutputLevel) {
		fmt.Printf(s)
	}
	if global.ConsoleSave && level >= LogLevel(global.ConsoleSaveLevel) {
		err := tools.WriteStringToLog(s, levelName+".log", "")
		if err != nil {
			fmt.Println("ERROR WriteStringToLog", err.Error())
		}
	}
}

/*
示例:
j_log.LogDebug([]interface{}{"debug "})
j_log.LogError([]interface{}{"端口被占用", 6379, []byte{0x06, 0xff}, struct {
	Name string
	Age  uint8
}{
	"Jiang", 33,
}})
j_log.LogInfo([]interface{}{"info"})

*/
